/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ListView,
  TextInput,
  Image,
  ScrollView,
  Dimensions,
  DeviceEventEmitter
} from 'react-native';

import Common from '../../component/common';

import SubscriptionItem from '../me/part/subscriptionItem';
import InfoItem from '../me/part/infoItem';
import VarietyItem from '../me/part/varietyItem';

import Loading from '../../component/loading';
import ScreenUtils from '../../component/ScreenUtils';

import LoadError from '../../component/loadError';



const pheight= Dimensions.get('window').height

export default class searchList extends Component {
  constructor(props) {
    super(props);
    this.state = {
	    dataSource: new ListView.DataSource({
	    	rowHasChanged: (row1, row2) => row1 !== row2,
	    }),
		loading: true,
	    success: false,
	    errorMessage: "",
    }; 
    this.fetchData = this.fetchData.bind(this); 
  }
  componentDidMount() {
	this.setState({
		userInput:this.props.keyWords,	
		pageForward:this.props.keyValue,
	})
	this.searchData = DeviceEventEmitter.addListener('searchData', (data) => {
		this.setState({
			loading:true
		})
		this.fetchData();
	});
    this.fetchData();
  }
  componentWillUnmount() {
  	this.searchData.remove();
  }
  fetchData(){
  	if(this.props.keyWords!=""){
	    let formData = new FormData();  
		formData.append("keywords",this.props.keyWords);
	    Common.fetchData("POST", "/search/topList", formData, (responseData) => {
			this.setState({
				dataSource: this.state.dataSource.cloneWithRows(responseData.listResult),
				dataLength:responseData.listResult.length,
				loading: false,
        success: true,
			 })
	    },() => {
	        this.setState({
	        	loading: false,
	            success: false,
	            errorMessage: "请求失败",
	        });
	    },() => {
	        this.setState({
	        	loading: false,
	            success: false,
	           	errorMessage: "网络错误",
	        });
	    });
  	}
  }
  
  renderClassify(result){
  	if(result.type ==8){
  		//专栏
		return(
		  	<View>
				<SubscriptionItem  
					chageThis = {this.state.pageForward}   
					showTitle={true} 
					pagation={result.count>result.list.length}
					totalPage={result.count} 
					sectionTitle={result.typeName} 
					data ={result.list} 
					showDeleteButton = {false}
					keywords={this.props.keyWords}
					search={true}
				/>
		  	</View>
		)  		
  	}else if(result.type ==5){
  		//资讯
  		return(
		  	<View>
		  		<InfoItem 
		  			chageThis = {this.state.pageForward} 
		  			data ={result.list} 
		  			pagation={result.count>result.list.length} 
		  			totalPage={result.count} 
		  			sectionTitle={result.typeName} 
		  			showTitle={true}  
		  			showDeleteButton = {false}
		  			keywords={this.props.keyWords}
		  			search={true}
		  		/>
		  	</View>
		)  
  	}else if(result.type ==1){
  		//综艺
   		return(
		  	<View>
		  		 <VarietyItem 
		  		 	chageThis = {this.state.pageForward} 
		  		 	showTitle={true} 
		  		 	data ={result} 
		  		 	pagation={result.count>result.list.length}
		  		 	totalPage={result.count}  
		  		 	showDeleteButton = {false}
		  		 	keywords={this.props.keyWords}
		  		 	type ={result.type}
		  		 	search={true}
		  		/>
		  	</View>
		)  		
  	}else if(result.type ==2){
  		//电影
  		return (
  			<View>
  				<VarietyItem 
  					chageThis = {this.state.pageForward} 
  					showTitle={true} 
  					data ={result} 
  					pagation={result.count>result.list.length}
  					totalPage={result.count}  
  					showDeleteButton = {false}
  					keywords={this.props.keyWords}
  					type ={result.type}
  					search={true}
  				/>
  			</View>
  		)
  	}else if(result.type ==3){
  		//电视剧
  		return (
  			<View>
  				<VarietyItem 
  					chageThis = {this.state.pageForward} 
  					showTitle={true} 
  					data ={result} 
  					pagation={result.count>result.list.length}
  					totalPage={result.count}  
  					showDeleteButton = {false}
  					keywords={this.props.keyWords}
  					type ={result.type}
  					search={true}
  					
  				/>
  			</View>
  		)
  	}
  }
  
  renderInfoItems(data,sectionID,rowID) {
  	var _scrollView: ScrollView;
  	let sourceImage ;
  	switch(data.scrabbleType){
  		case 'wechat':
  			sourceImage = wechat;
  			break;
  		case 'web':
  			sourceImage = web;
  			break;
  		default :
  			sourceImage = weibo;
  			break;
  	}
    return (
      <TouchableOpacity style ={styles.InfoItemContainer} onPress={() => Common.onForward(this.props.chageThis,Detail,"",data.id)}>
		<View style={styles.infoTitleWrap} >
			<Text style={styles.infoTitle} numberOfLines ={1}>{data.title}</Text>
		</View>
		<View style={styles.infoAbout}>
			<View style={styles.infoContent}>
  				<Image style={styles.infoAboutImage} source = {sourceImage}/> 
  				<Text style={styles.infoAboutText}>
  					<Text style={styles.infoText}>{data.company}</Text>
  				</Text>
  			</View>
  			<View style={styles.infoContent}>
  				<Image style={styles.infoAboutImage} source = {require('../../images/timer.png')}/> 
  				<Text style={styles.infoAboutText}>
  					<Text style={styles.infoText}>{Common.beforeTime(data.createTime,5)}</Text>
  				</Text>
  			</View>
  			{
  				data.sourceDegree ? 
  				(
  					parseFloat(data.sourceDegree)>0 ?
  						<View style={styles.infoContent}>
			  				<Text style={styles.infoAboutText}>
			  						<Text style={styles.infoText}>{data.sourceDegree}</Text> 阅读
			  				</Text>
			  			</View> :null
  				):null
  			}
		</View>
      </TouchableOpacity>
    );
  }
  
  render() {
  	if(this.state.loading){
  		return <Loading style={{marginTop:pheight/2-60}}/>
  	}else{
  		if(this.state.success){
		  	return (
				<View style={styles.content}>
					{
						this.state.dataLength > 0 ?
						<ListView
				          dataSource={this.state.dataSource}
				          renderRow={this.renderClassify.bind(this)}  
				          enableEmptySections={true}
				          removeClippedSubviews={false}
				          keyboardShouldPersistTaps ="always"
				      	/> : <View style={styles.nodata}><Text>没有搜索到相关信息</Text></View>
					}
				</View >
		  	)  				
  		}else{
  			return <LoadError style={{marginTop:pheight/2-60}} reload={this.fetchData}  reason={this.state.errorMessage}/>
  		}
    }
  }
 
}

const styles = StyleSheet.create({
  type:{
  	fontSize:13,
  	color:"#939393",
  	paddingTop:13,
  	paddingBottom:13,
  	paddingLeft:15,
  	paddingRight:12,
  	backgroundColor:'#f6f6f6',
  },
  bg:{
  	backgroundColor:'#fff',
  },
  content:{
  	backgroundColor:'#f6f6f6',
  	marginBottom:ScreenUtils.scaleSize(78),
  },
  nodata:{
  	flex:1,
  	height:pheight-ScreenUtils.scaleSize(155),
  	justifyContent: 'center',
    alignItems: 'center',
  }
});